import { createApp, ref, h, reactive, watchEffect } from 'vue'
import HandDrawnConfirm from '@/components/HandDrawnConfirm.vue'

// 确认对话框选项接口
interface HandDrawnConfirmOptions {
  type?: 'warning' | 'info' | 'success' | 'error' | 'question'
  title?: string
  message?: string
  confirmButtonText?: string
  cancelButtonText?: string
  closeOnClickModal?: boolean
}

// 全局状态
let currentInstance: any = null

// 主要的确认函数
export const handDrawnConfirm = (
  message: string,
  title?: string,
  options?: HandDrawnConfirmOptions
): Promise<boolean> => {
  return new Promise((resolve) => {
    // 如果已有实例，先清理
    if (currentInstance) {
      currentInstance.unmount()
      currentInstance = null
    }

    // 创建容器
    const container = document.createElement('div')
    container.id = 'hand-drawn-confirm-container-' + Date.now()
    document.body.appendChild(container)

    // 设置默认选项
    const finalOptions = {
      type: 'warning' as const,
      title: title || '确认操作',
      message,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: true,
      ...options
    }

    // 创建响应式状态
    const state = reactive({
      visible: true,
      ...finalOptions
    })

    // 事件处理函数
    const handleConfirm = () => {
      cleanup()
      resolve(true)
    }

    const handleCancel = () => {
      cleanup()
      resolve(false)
    }

    const handleUpdateVisible = (value: boolean) => {
      state.visible = value
      if (!value) {
        setTimeout(() => {
          cleanup()
          resolve(false)
        }, 300)
      }
    }

    // 清理函数
    const cleanup = () => {
      state.visible = false
      if (currentInstance) {
        setTimeout(() => {
          if (currentInstance) {
            currentInstance.unmount()
            currentInstance = null
          }
          if (container && document.body.contains(container)) {
            document.body.removeChild(container)
          }
        }, 300)
      }
    }

    // 创建组件实例
    const ComponentWrapper = {
      setup() {
        // 使用watchEffect确保响应式更新
        return () => {
          return h(HandDrawnConfirm, {
            visible: state.visible,
            type: state.type,
            title: state.title,
            message: state.message,
            confirmButtonText: state.confirmButtonText,
            cancelButtonText: state.cancelButtonText,
            closeOnClickModal: state.closeOnClickModal,
            'onUpdate:visible': handleUpdateVisible,
            onConfirm: handleConfirm,
            onCancel: handleCancel
          })
        }
      }
    }

    // 挂载组件
    currentInstance = createApp(ComponentWrapper)
    currentInstance.mount(container)

    // 添加键盘监听
    const handleKeydown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        handleCancel()
        document.removeEventListener('keydown', handleKeydown)
      } else if (event.key === 'Enter') {
        handleConfirm()
        document.removeEventListener('keydown', handleKeydown)
      }
    }
    document.addEventListener('keydown', handleKeydown)

    // 确保在下一个tick后初始化边框
    setTimeout(() => {
      const confirmComponent = container.querySelector('.hand-drawn-confirm-card')
      if (confirmComponent) {
        // 触发resize事件来初始化边框
        const event = new Event('resize')
        window.dispatchEvent(event)
      }
    }, 100)
  })
}

// 便捷方法
export const HandDrawnMessageBox = {
  confirm: handDrawnConfirm,

  warning: (message: string, title?: string, options?: Omit<HandDrawnConfirmOptions, 'type'>) =>
    handDrawnConfirm(message, title, { ...options, type: 'warning' }),

  info: (message: string, title?: string, options?: Omit<HandDrawnConfirmOptions, 'type'>) =>
    handDrawnConfirm(message, title, { ...options, type: 'info' }),

  success: (message: string, title?: string, options?: Omit<HandDrawnConfirmOptions, 'type'>) =>
    handDrawnConfirm(message, title, { ...options, type: 'success' }),

  error: (message: string, title?: string, options?: Omit<HandDrawnConfirmOptions, 'type'>) =>
    handDrawnConfirm(message, title, { ...options, type: 'error' }),

  question: (message: string, title?: string, options?: Omit<HandDrawnConfirmOptions, 'type'>) =>
    handDrawnConfirm(message, title, { ...options, type: 'question' })
}

// 清理函数
export const destroyConfirm = () => {
  if (currentInstance) {
    currentInstance.unmount()
    currentInstance = null
  }
  // 清理所有可能存在的容器
  const containers = document.querySelectorAll('[id^="hand-drawn-confirm-container-"]')
  containers.forEach(container => {
    if (document.body.contains(container)) {
      document.body.removeChild(container)
    }
  })
}

// 默认导出
export default handDrawnConfirm 